package com.tonann.app.controller;

import com.tonann.app.domain.AppDevice;
import com.tonann.app.domain.AppGateway;
import com.tonann.app.domain.AppProject;
import com.tonann.app.domain.AppSensor;
import com.tonann.app.dto.AppDeviceDto;
import com.tonann.app.service.IAppDeviceService;
import com.tonann.app.service.IAppGatewayService;
import com.tonann.app.service.IAppProjectService;
import com.tonann.app.service.IAppSensorService;
import com.tonann.app.websocket.MsgType;
import com.tonann.app.websocket.SocketMsg;
import com.tonann.app.websocket.WebSocketServer;
import com.tonann.common.annotation.Log;
import com.tonann.common.constant.UserConstants;
import com.tonann.common.core.controller.BaseController;
import com.tonann.common.core.domain.AjaxResult;
import com.tonann.common.core.domain.entity.SysDept;
import com.tonann.common.core.domain.entity.SysPlace;
import com.tonann.common.core.domain.entity.SysUser;
import com.tonann.common.enums.BusinessType;
import com.tonann.common.utils.StringUtils;
import com.tonann.common.utils.bean.BeanUtils;
import com.tonann.common.utils.poi.ExcelUtil;
import com.tonann.system.service.ISysDeptService;
import com.tonann.system.service.ISysDictDataService;
import com.tonann.system.service.ISysPlaceService;
import com.tonann.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 运行设备Controller
 *
 * @author tonann
 * @date 2022-10-12
 */
@RestController
@RequestMapping("/app/device")
public class AppDeviceController extends BaseController {
    @Resource
    private IAppDeviceService appDeviceService;

    @Resource
    private IAppSensorService appSensorService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysPlaceService placeService;

    @Resource
    private ISysDictDataService dictDataService;
    @Resource
    private IAppProjectService appProjectService;
    @Resource
    private IAppGatewayService appGatewayService;

    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private ISysPlaceService sysPlaceService;
    @Resource
    private ISysUserService sysUserService;

    private Logger log = LoggerFactory.getLogger(AppDeviceController.class);

    /**
     * 查询运行设备列表
     */
    @PreAuthorize("@ss.hasPermi('app:device:list')")
    @GetMapping("/list")
    public AjaxResult list(AppDevice appDevice) {
        List<AppDevice> appDeviceList = appDeviceService.selectAppDeviceList(appDevice);
        List<AppDeviceDto> dtoList = new ArrayList<>();
        for (AppDevice device : appDeviceList){
            AppDeviceDto dto = new AppDeviceDto();
            BeanUtils.copyProperties(device,dto);
            dto.setProjectName(device.getAppProject().getProjectName());
            dto.setGatewayName(device.getAppGateway().getGatewayName());
            dtoList.add(dto);
        }
        return AjaxResult.success(dtoList);
    }

    /**
     * 查询运行设备列表
     */
    @PreAuthorize("@ss.hasPermi('app:device:list')")
    @GetMapping("/list/simple")
    public AjaxResult listSimple(AppDevice appDevice) {
        List<AppDevice> appDeviceList = appDeviceService.selectAppDeviceListSimple(appDevice);
        List<AppDeviceDto> dtoList = new ArrayList<>();
        for (AppDevice device : appDeviceList){
            AppDeviceDto dto = new AppDeviceDto();
            BeanUtils.copyProperties(device,dto);
            dtoList.add(dto);
        }
        return AjaxResult.success(dtoList);
    }

    /**
     * 查询设备列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('app:device:list')")
    @GetMapping("/list/exclude/{deviceId}")
    public AjaxResult excludeChild(@PathVariable(value = "deviceId", required = false) Long deviceId) {
        List<AppDevice> devices = appDeviceService.selectAppDeviceAll(new AppDevice());
        devices.removeIf(d -> d.getDeviceId().intValue() == deviceId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deviceId + ""));
        List<AppDeviceDto> dtoList = new ArrayList<>();
        for (AppDevice device : devices){
            AppDeviceDto dto = new AppDeviceDto();
            BeanUtils.copyProperties(device,dto);
            dtoList.add(dto);
        }
        return AjaxResult.success(dtoList);
    }

    @PreAuthorize("@ss.hasPermi('app:device:list')")
    @GetMapping("/list/admin/{deviceId}")
    public AjaxResult listAdmin(@PathVariable(value = "deviceId", required = false) Long deviceId) {
        List<SysUser> sysUsers = appDeviceService.selectUserByDeviceId(deviceId, "1");
        return AjaxResult.success(sysUsers);
    }

    @PreAuthorize("@ss.hasPermi('app:device:list')")
    @GetMapping("/list/operator/{deviceId}")
    public AjaxResult listOperator(@PathVariable(value = "deviceId", required = false) Long deviceId) {
        List<SysUser> sysUsers = appDeviceService.selectUserByDeviceId(deviceId, "2");
        return AjaxResult.success(sysUsers);
    }

    /**
     * 导出运行设备列表
     */
    @PreAuthorize("@ss.hasPermi('app:device:export')")
    @Log(title = "运行设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppDevice appDevice) {
        List<AppDevice> list = appDeviceService.selectAppDeviceList(appDevice);
        ExcelUtil<AppDevice> util = new ExcelUtil<AppDevice>(AppDevice.class);
        util.exportExcel(response, list, "运行设备数据");
    }

    /**
     * 获取运行设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('app:device:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        AppDevice appDevice = appDeviceService.selectAppDeviceByDeviceId(deviceId);
        List<Long> adminIds = appDeviceService.selectAppDeviceAdminListByDeviceId(deviceId);
        List<Long> operatorIds = appDeviceService.selectAppDeviceOperatorListByDeviceId(deviceId);
        appDevice.setAdminIds(adminIds.toArray(new Long[adminIds.size()]));
        appDevice.setOperatorIds(operatorIds.toArray(new Long[operatorIds.size()]));
        return AjaxResult.success(appDevice);
    }

    /**
     * 复制设备
     */
    @PreAuthorize("@ss.hasPermi('app:device:add')")
    @GetMapping(value = "/copy")
    public AjaxResult copyDevice(Long deviceId, Integer num) throws Exception {
        AppDevice appDevice = appDeviceService.selectAppDeviceByDeviceId(deviceId);
        if (appDevice != null) {
            List<Long> adminIds = appDeviceService.selectAppDeviceAdminListByDeviceId(deviceId);
            List<Long> operatorIds = appDeviceService.selectAppDeviceOperatorListByDeviceId(deviceId);
            appDevice.setAdminIds(adminIds.toArray(new Long[0]));
            appDevice.setOperatorIds(operatorIds.toArray(new Long[0]));
            List<Long> placeIds = appDeviceService.selectAppDevicePlaceListByDeviceId(deviceId);
            List<Long> deptIds = appDeviceService.selectAppDeviceDeptListByDeviceId(deviceId);
            appDevice.setPlaceIds(placeIds.toArray(new Long[0]));
            appDevice.setDeptIds(deptIds.toArray(new Long[0]));
            String deviceName = appDevice.getDeviceName();
            Integer index = this.getNum(deviceName);
            for (int i = 0; i < num; i++) {
                String newName = "";
                int add = i + 1;
                if (index == null) {
                    newName = deviceName + (i < 10 ? "0" + Integer.toString(add) : "" + i);
                } else {
                    newName = deviceName.replace(index.toString(), index + Integer.toString(add));
                }
                appDevice.setDeviceName(newName);
                appDevice.setDeviceId(null);
                appDeviceService.insertAppDevice(appDevice);
                if (appDevice.getDeviceId() != null) {
                    appDeviceService.authDataScope(appDevice);
                    appDeviceService.authPlaceScope(appDevice);
                }
                AppSensor appSensor = new AppSensor();
                appSensor.setDeviceId(deviceId);
                List<AppSensor> sensorList = appSensorService.selectAppSensorAllList(appSensor);
                for (int j = 0; j < sensorList.size(); j++) {
                    AppSensor sensor = sensorList.get(i);
                    sensor.setMqttDeviceTag(sensor.getMqttDeviceTag() + "_copy_" + i + 1);
                    sensor.setSensorCode(sensor.getSensorCode() + "_copy_" + i + 1);
                    sensor.setSensorName(sensor.getSensorName() + "_copy_" + i + 1);
                    List<Long> sensorDeptIds = appSensorService.selectAppSensorDeptListBySensorId(sensor.getSensorId());
                    List<Long> sensorPlaceIds = appSensorService.selectAppSensorDeptListBySensorId(sensor.getSensorId());
                    sensor.setPlaceIds(sensorPlaceIds.toArray(new Long[sensorPlaceIds.size()]));
                    sensor.setDeptIds(sensorDeptIds.toArray(new Long[sensorDeptIds.size()]));
                    sensor.setSensorId(null);
                    sensor.setDeviceId(appDevice.getDeviceId());
                    appSensorService.insertAppSensor(sensor);
                    if (sensor.getSensorId() != null) {
                        appSensorService.authDeptScope(sensor);
                        appSensorService.authPlaceScope(sensor);
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 新增运行设备
     */
    @PreAuthorize("@ss.hasPermi('app:device:add')")
    @Log(title = "运行设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppDevice appDevice) throws Exception {
        if (UserConstants.NOT_UNIQUE.equals(appDeviceService.checkAppDeviceNameUnique(appDevice))) {
            return AjaxResult.error("新增设备'" + appDevice.getDeviceName() + "'失败，设备名称已存在");
        }
        appDevice.setCreateBy(getUsername());
        appDevice.setUpdateBy(getUsername());
        return AjaxResult.success(appDeviceService.insertAppDevice(appDevice));
    }

    /**
     * 修改运行设备
     */
    @PreAuthorize("@ss.hasPermi('app:device:edit')")
    @Log(title = "运行设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppDevice appDevice) throws Exception {
        Long appDeviceId = appDevice.getDeviceId();
        if (UserConstants.NOT_UNIQUE.equals(appDeviceService.checkAppDeviceNameUnique(appDevice))) {
            return AjaxResult.error("修改设备'" + appDevice.getDeviceName() + "'失败，设备名称已存在");
        } else if (appDevice.getParentId().equals(appDeviceId)) {
            return AjaxResult.error("修改设备'" + appDevice.getDeviceName() + "'失败，上级设备不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, appDevice.getStatus()) && appDeviceService.selectNormalChildrenAppDeviceById(appDeviceId) > 0) {
            return AjaxResult.error("该设备包含未停用的子设备！");
        }
        appDevice.setUpdateBy(getUsername());
        return toAjax(appDeviceService.updateAppDevice(appDevice));
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('app:device:edit')")
    @Log(title = "运行设备", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody AppDevice device) {
        appDeviceService.checkDeviceDataScope(device.getDeviceId());
        return toAjax(appDeviceService.authDataScope(device));
    }


    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('app:device:edit')")
    @Log(title = "运行设备", businessType = BusinessType.UPDATE)
    @PutMapping("/placeScope")
    public AjaxResult placeScope(@RequestBody AppDevice device) {
        appDeviceService.checkDevicePlaceScope(device.getDeviceId());
        return toAjax(appDeviceService.authPlaceScope(device));
    }

    /**
     * 删除运行设备
     */
    @PreAuthorize("@ss.hasPermi('app:device:remove')")
    @Log(title = "运行设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceId}")
    public AjaxResult remove(@PathVariable Long deviceId) {
        if (appDeviceService.hasChildByAppDeviceId(deviceId)) {
            return AjaxResult.error("存在下级设备,不允许删除");
        }
        if (appDeviceService.checkAppDeviceExistUser(deviceId)) {
            return AjaxResult.error("设备存在用户,不允许删除");
        }
        return toAjax(appDeviceService.deleteAppDeviceByDeviceId(deviceId));
    }

    /**
     * 获取对应角色设备树列表
     */
    @PreAuthorize("@ss.hasPermi('app:device:query')")
    @GetMapping(value = "/deptTree/{deviceId}")
    public AjaxResult deptTree(@PathVariable("deviceId") Long deviceId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", appDeviceService.selectAppDeviceDeptListByDeviceId(deviceId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }

    /**
     * 获取对应角色空间位置树列表
     */
    @PreAuthorize("@ss.hasPermi('app:device:query')")
    @GetMapping(value = "/placeTree/{deviceId}")
    public AjaxResult placeTree(@PathVariable("deviceId") Long deviceId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", appDeviceService.selectAppDevicePlaceListByDeviceId(deviceId));
        ajax.put("places", placeService.selectPlaceTreeList(new SysPlace()));
        return ajax;
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('app:device:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,String sid) {
        try {
            ExcelUtil<AppDeviceDto> util = new ExcelUtil<AppDeviceDto>(AppDeviceDto.class);
            List<AppDeviceDto> dtoList = util.importExcel(file.getInputStream());
            String userName = getUsername();
            double verifyTime = dtoList.size() * 1.2;
            double addTime = dtoList.size() * 1.6;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        sendMsg("服务器收到文件", MsgType.INFO,sid);
                        boolean isError = false;
                        List<AppDevice> deviceList = new ArrayList<>();
                        Map<String,List<AppDeviceDto>> deviceNameMap = dtoList.stream().collect(Collectors.groupingBy(AppDeviceDto::getDeviceName));
                        Map<String,List<AppDeviceDto>> deviceCodeMap = dtoList.stream().collect(Collectors.groupingBy(AppDeviceDto::getDeviceCode));
                        for(List<AppDeviceDto> deviceDtoList : deviceNameMap.values()){
                            if (deviceDtoList.size() > 1){
                                sendMsg("表中设备名称：" + deviceDtoList.get(0).getDeviceName() + "  重复",MsgType.ERROR,sid);
                                isError = true;
                            }
                        }
                        for(List<AppDeviceDto> deviceDtoList : deviceCodeMap.values()){
                            if (deviceDtoList.size() > 1){
                                sendMsg("表中设备编号：" + deviceDtoList.get(0).getDeviceCode() + "  重复",MsgType.ERROR,sid);
                                isError = true;
                            }
                        }
                        if (isError) {
                            return;
                        }
                        List<AppDevice> allDeviceList = appDeviceService.selectAppDeviceAll(new AppDevice());
                        Map<String,List<AppDevice>> allDeviceNameMap = allDeviceList.stream().collect(Collectors.groupingBy(AppDevice::getDeviceName));
                        Map<String,List<AppDevice>> allDeviceCodeMap = allDeviceList.stream().collect(Collectors.groupingBy(AppDevice::getDeviceCode));
                        List<AppProject> allProjectList = appProjectService.selectAppProjectList(new AppProject());
                        Map<String,List<AppProject>> allProjectNameMap = allProjectList.stream().collect(Collectors.groupingBy(AppProject::getProjectName));
                        List<AppGateway> allGateWayList = appGatewayService.selectAppGatewayList(new AppGateway());
                        Map<String ,List<AppGateway>> allGateWayNameMap = allGateWayList.stream().collect(Collectors.groupingBy(AppGateway::getGatewayName));
                        for (int i = 0; i < dtoList.size(); i++) {
                            AppDeviceDto dto = dtoList.get(i);
                            String error = verifyExcelRowData(dto, i + 1, deviceList,allDeviceNameMap,allDeviceCodeMap,allProjectNameMap,allGateWayNameMap);
                            if (error != null) {
                                sendMsg(error, MsgType.ERROR,sid);
                                isError = true;
                            }
                        }
                        if (isError) {
                            return;
                        }
                        sendMsg("验证完成，正在进行导入...", MsgType.INFO,sid);
                        int j = 0;
                        for (AppDevice device : deviceList) {
                            device.setStatus("0");
                            device.setDeptCheckStrictly(true);
                            device.setPlaceCheckStrictly(true);
                            device.setCreateBy(userName);
                            device.setUpdateBy(userName);
                            appDeviceService.insertAppDevice(device);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        sendMsg("新增数据异常", MsgType.ERROR,sid);
                        return;
                    }
                    sendMsg("导入成功", MsgType.INFO,sid);
                }
            }).start();
            Map<String,String> map = new HashMap<>();
            map.put("verifyTime",String.valueOf(verifyTime));
            map.put("addTime",String.valueOf(addTime));
            return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("导入数据错误");
        }
    }

    /**
     * 通过实现handle方法编写我们要对每行数据的操作方式
     */
    private String verifyExcelRowData(AppDeviceDto dto, int rowIndex, List<AppDevice> list,
                                      Map<String,List<AppDevice>> allDeviceNameMap,
                                      Map<String,List<AppDevice>> allDeviceCodeMap,
                                      Map<String,List<AppProject>> allProjectNameMap,
                                      Map<String ,List<AppGateway>> allGateWayNameMap
                                      ) {
        AppDevice device = new AppDevice();
        String parentName = dto.getParentName();
        String projectName = dto.getProjectName();
        String gatewayName = dto.getGatewayName();
        String deviceCode = dto.getDeviceCode();
        String deviceName = dto.getDeviceName();
        String manufactor = dto.getManufactor();
        String brand = dto.getBrand();
        String model = dto.getModel();
        Date acquisitionDate = dto.getAcquisitionDate();
        String maintenanceUnit = dto.getMaintenanceUnit();
        Date maintenanceDate = dto.getMaintenanceDate();
        String isShow = dto.getIsShow();
        String type = dto.getType();
        String deptName = dto.getDeptName();
        String placeName = dto.getPlaceName();
        String admin = dto.getAdmin();
        String operator = dto.getOperator();
        if (parentName != null && !parentName.trim().isEmpty()) {
            List<AppDevice> parentDeviceList = allDeviceNameMap.get(parentName);
            if (parentDeviceList == null || parentDeviceList.isEmpty()) {
                return "第" + (rowIndex) + "行,上级设备不存在";
            } else if (parentDeviceList.size() > 1) {
                return "第" + (rowIndex) + "行,上级设备有多个";
            } else {
                device.setParentId(parentDeviceList.get(0).getDeviceId());
            }
        } else {
            device.setParentId(0L);
        }
        if (projectName != null && !projectName.trim().isEmpty()) {
            List<AppProject> projectList = allProjectNameMap.get(projectName);
            if (projectList == null || projectList.isEmpty()) {
                return "第" + (rowIndex) + "行,项目不存在";
            } else if (projectList.size() > 1) {
                return "第" + (rowIndex) + "行,项目有多个";
            } else {
                device.setProjectId(projectList.get(0).getProjectId());
            }
        } else {
            return "第" + (rowIndex) + "行,项目名称为空";
        }

        if (gatewayName != null && !gatewayName.trim().isEmpty()) {
            List<AppGateway> gatewayList = appGatewayService.selectAppGatewayByGatewayName(gatewayName);
            if (gatewayList.isEmpty()) {
                return "第" + (rowIndex) + "行,网关不存在";
            } else if (gatewayList.size() > 1) {
                return "第" + (rowIndex) + "行,相同名字网关有多个";
            } else {
                device.setGatewayId(gatewayList.get(0).getGatewayId());
            }
        } else {
            return "第" + (rowIndex) + "行,网关名称为空";
        }
        if (deviceCode != null && !deviceCode.trim().isEmpty()) {
            List<AppDevice> deviceList = allDeviceCodeMap.get(deviceCode);
            if (deviceList == null || deviceList.isEmpty()) {
                device.setDeviceCode(deviceCode);
            } else {
                return "第" + (rowIndex) + "行,设备编号重复";
            }
        } else {
            return "第" + (rowIndex) + "行,设备编号为空";
        }

        if (deviceName != null && !deviceName.trim().isEmpty()) {
            List<AppDevice> deviceList = appDeviceService.selectAppDeviceByDeviceName(deviceName.trim());
            if (deviceList.isEmpty()) {
                device.setDeviceName(deviceName);
            } else {
                return "第" + (rowIndex) + "行,设备名称重复";
            }
        } else {
            return "第" + (rowIndex) + "行,设备名称为空";
        }
        if (manufactor != null && !manufactor.trim().isEmpty()) {
            device.setManufactor(manufactor);
        }
        if (brand != null && !brand.trim().isEmpty()) {
            device.setBrand(brand);
        }
        if (model != null && !model.trim().isEmpty()) {
            device.setModel(model);
        }
        if (acquisitionDate != null) {
            device.setAcquisitionDate(acquisitionDate);
        }
        if (maintenanceUnit != null && !maintenanceUnit.trim().isEmpty()) {
            device.setMaintenanceUnit(maintenanceUnit);
        }
        if (maintenanceDate != null) {
            device.setMaintenanceDate(maintenanceDate);
        }

        if (isShow != null && !isShow.trim().isEmpty()) {
            if (isShow.equals("是")) {
                device.setIsShow("1");
            } else if (isShow.equals("否")) {
                device.setIsShow("0");
            } else {
                return "第" + (rowIndex) + "行,是否演示设备填写不规范";
            }
        } else {
            return "第" + (rowIndex) + "行,是否演示设备为空";
        }
        if (type != null && !type.trim().isEmpty()) {
            String dictValue = dictDataService.selectDictValue("app_device_type", type);
            if (dictValue != null) {
                device.setType(dictValue);
            } else {
                return "第" + (rowIndex) + "行,设备类型不存在";
            }
        } else {
            return "第" + (rowIndex) + "行,设备类型为空";
        }
        List<Long> deptIds = new ArrayList<>();
        if (deptName != null && !deptName.trim().isEmpty()) {
            List<String> deptNames = getMultiName(deptName);
            for (String name : deptNames) {
                name = name.replaceAll(":", ":");
                name = name.replaceAll("：", ":");
                String[] names = name.split(":");
                SysDept parentDept = null;
                for (int i = 0; i < names.length; i++) {
                    String n = names[i];
                    if (n != null && !n.trim().isEmpty()) {
                        List<SysDept> deptList = sysDeptService.selectDeptByDeptName(n.trim());
                        if (i == 0) {
                            List<SysDept> firstDeptList = deptList.stream().filter(item -> item.getParentId() == null || item.getParentId() == 0L).collect(Collectors.toList());
                            if (firstDeptList.isEmpty()) {
                                parentDept = new SysDept();
                                parentDept.setParentId(0L);
                                parentDept.setDeptName(n.trim());
                                parentDept.setAncestors("0");
                                parentDept.setStatus("0");
                                sysDeptService.insertDept(parentDept);
                                if (parentDept.getDeptId() == null) ;
                                {
                                    parentDept.setAncestors(null);
                                    List<SysDept> sysDeptList = sysDeptService.selectDeptAll(parentDept);
                                    if (!sysDeptList.isEmpty()) {
                                        parentDept = sysDeptList.get(0);
                                    }
                                }
                            } else if (firstDeptList.size() > 1) {
                                return "第" + (rowIndex) + "行,部门第一级部门存在多个数据";
                            } else {
                                parentDept = firstDeptList.get(0);
                            }
                        } else if (parentDept != null) {
                            final Long parentId = parentDept.getDeptId();
                            if (parentId != null) {
                                List<SysDept> elseDeptList = deptList.stream().filter(item -> item.getParentId() != null && item.getParentId().equals(parentId)).collect(Collectors.toList());
                                if (elseDeptList.isEmpty()) {
                                    parentDept = new SysDept();
                                    parentDept.setParentId(parentId);
                                    parentDept.setDeptName(n.trim());
                                    parentDept.setStatus("0");
                                    sysDeptService.insertDept(parentDept);
                                    if (parentDept.getDeptId() == null) ;
                                    {
                                        List<SysDept> sysDeptList = sysDeptService.selectDeptAll(parentDept);
                                        if (!sysDeptList.isEmpty()) {
                                            parentDept = sysDeptList.get(0);
                                        }
                                    }
                                } else if (elseDeptList.size() > 1) {
                                    return "第" + (rowIndex) + "行,部门存在多个数据";
                                } else {
                                    parentDept = elseDeptList.get(0);
                                }
                            }
                        }
                        if (parentDept != null && parentDept.getDeptId() != null && i == names.length - 1) {
                            deptIds.add(parentDept.getDeptId());
                        }
                    }
                }
            }
        }
        device.setDeptIds(deptIds.toArray(new Long[0]));

        List<Long> placeIds = new ArrayList<>();
        if (placeName != null && !placeName.trim().isEmpty()) {
            List<String> placeNames = getMultiName(placeName);
            for (String name : placeNames) {
                name = name.replaceAll(":", ":");
                name = name.replaceAll("：", ":");
                String[] names = name.split(":");
                SysPlace parentPlace = null;
                for (int i = 0; i < names.length; i++) {
                    String n = names[i];
                    if (n != null && !n.trim().isEmpty()) {
                        List<SysPlace> placeList = sysPlaceService.selectPlaceByPlaceName(n.trim());
                        if (i == 0) {
                            List<SysPlace> firstPlaceList = placeList.stream().filter(item -> item.getParentId() == null || item.getParentId() == 0L).collect(Collectors.toList());
                            if (firstPlaceList.isEmpty()) {
                                parentPlace = new SysPlace();
                                parentPlace.setParentId(0L);
                                parentPlace.setPlaceName(n.trim());
                                parentPlace.setAncestors("0");
                                parentPlace.setStatus("0");
                                sysPlaceService.insertPlace(parentPlace);
                                if (parentPlace.getParentId() == null) {
                                    parentPlace.setAncestors(null);
                                    List<SysPlace> sysPlaceList = sysPlaceService.selectPlaceAll(parentPlace);
                                    if (!sysPlaceList.isEmpty()) {
                                        parentPlace = sysPlaceList.get(0);
                                    }
                                }
                            } else if (firstPlaceList.size() > 1) {
                                return "第" + (rowIndex) + "行,空间位置第一级位置存在多个数据";
                            } else {
                                parentPlace = firstPlaceList.get(0);
                            }
                        } else if (parentPlace != null) {
                            final Long parentId = parentPlace.getPlaceId();
                            if (parentId != null) {
                                List<SysPlace> elsePlaceList = placeList.stream().filter(item -> item.getParentId() != null && item.getParentId().equals(parentId)).collect(Collectors.toList());
                                if (elsePlaceList.isEmpty()) {
                                    parentPlace = new SysPlace();
                                    parentPlace.setParentId(parentId);
                                    parentPlace.setPlaceName(n.trim());
                                    parentPlace.setAncestors("0");
                                    parentPlace.setStatus("0");
                                    sysPlaceService.insertPlace(parentPlace);
                                    if (parentPlace.getPlaceId() == null) {
                                        List<SysPlace> sysPlaceList = sysPlaceService.selectPlaceAll(parentPlace);
                                        if (!sysPlaceList.isEmpty()) {
                                            parentPlace = sysPlaceList.get(0);
                                        }
                                    }
                                } else if (elsePlaceList.size() > 1) {
                                    return "第" + (rowIndex) + "行,空间位置存在多个数据";
                                } else {
                                    parentPlace = elsePlaceList.get(0);
                                }
                            }
                        }
                        if (parentPlace != null && parentPlace.getPlaceId() != null && i == names.length - 1) {
                            placeIds.add(parentPlace.getPlaceId());
                        }
                    }
                }
            }
        }
        device.setPlaceIds(placeIds.toArray(new Long[0]));
        Set<Long> adminIds = new HashSet<>();
        if (admin != null && !admin.trim().isEmpty()) {
            admin = admin.trim();
            List<String> adminNames = getMultiName(admin);
            for (String userName : adminNames) {
                if (!userName.trim().isEmpty()) {
                    SysUser sysUser = sysUserService.selectUserByUserName(userName.trim());
                    if (sysUser != null) {
                        adminIds.add(sysUser.getUserId());
                    } else {
                        return "第" + (rowIndex) + "行,有管理员不存在";
                    }
                }
            }
        }
        device.setAdminIds(adminIds.toArray(new Long[0]));
        Set<Long> operatorIds = new HashSet<>();
        if (operator != null && !operator.trim().isEmpty()) {
            operator = operator.trim();
            List<String> operatorNames = getMultiName(operator);
            for (String userName : operatorNames) {
                if (!userName.trim().isEmpty()) {
                    SysUser sysUser = sysUserService.selectUserByUserName(userName.trim());
                    if (sysUser != null) {
                        operatorIds.add(sysUser.getUserId());
                    } else {
                        return "第" + (rowIndex) + "行,有操作员不存在";
                    }
                }
            }
        }
        device.setOperatorIds(operatorIds.toArray(new Long[0]));
        list.add(device);
        return null;
    }

    private void sendMsg(String msg, MsgType msgType,String sid) {
        try {
            WebSocketServer.sendInfo(new SocketMsg(msg, msgType), sid);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<AppDeviceDto> util = new ExcelUtil<AppDeviceDto>(AppDeviceDto.class);
        util.importTemplateExcel(response, "sheet1");
    }

    private Integer getNum(String str) {
        Integer num = null;
        String str1 = "";
        int index = -2;
        if (str != null && !"".equals(str.trim())) {
            str = str.trim();
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    if (index == -2) {
                        index = i;
                        str1 = "" + str.charAt(i);
                    } else if (index == i - 1) {
                        str1 += str.charAt(i);
                    } else {
                        str1 = "" + str.charAt(i);
                        index = i;
                    }
                }
            }
        }
        if (!"".equals(str1)) {
            num = Integer.parseInt(str1);
        }
        return num;
    }

    private List<String> getMultiName(String name) {
        name = name.replaceAll(",", ",");
        name = name.replaceAll("，", ",");
        return getSplit(name, ",");
    }

    private List<String> getSplit(String str, String split) {
        return Arrays.asList(str.split(split));
    }
}
